package org.ggn.dao;

import org.ggn.exception.CourseException;
import org.ggn.model.Course;
import org.ggn.util.HibernateUtil;
import org.hibernate.Session;

public class CourseDao implements CDao {

	@Override
	public void add(Course c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			if(c.getName()==null){
				throw new CourseException("课程不能为空");
			}
			/*if(c.getExam_info()==null){
				throw new CourseException("资料地址不能为空");
			}*/
			Course u = (Course) session.createQuery("select us from Course us where name like ?")
					.setParameter(0,c.getName()).uniqueResult();
			if(u!=null){
				throw new CourseException("课程已存在");
			}
			session.save(c);
			
			session.getTransaction().commit();
		} 
		finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public void delete(Course c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			
			session.delete(c);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if(session!=null){
				session.getTransaction().rollback();
			}
		}finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public void update(Course c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			Course u = (Course)session.load(Course.class, c.getId());
			if(u==null){
				throw new CourseException("更新的课程不存在");
			}
			u.setName(c.getName());
			u.setExam_info(c.getExam_info());
			u.setpaper_year_an(c.getpaper_year_an());
			u.setpaper_year_noan(c.getpaper_year_noan());
			session.update(u);
			
			session.getTransaction().commit();
		} finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public Course load(int id) {
		Session session = null;
		Course u = null;
		try {
			session = HibernateUtil.openSession();
			if(id==0){
				throw new CourseException("查找不存在");
			}
			//u = (Course)session.load(Course.class, id);
			u = (Course)session.get(Course.class, id);
			return u;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtil.close(session);
		}
		return u;
	}

}
